package cn.shoptnt.service.trade.order.command.impl;

import cn.hutool.core.collection.CollUtil;
import cn.shoptnt.client.member.MemberClient;
import cn.shoptnt.client.promotion.CouponClient;
import cn.shoptnt.model.member.dos.MemberCoupon;
import cn.shoptnt.model.promotion.coupon.vo.GoodsCouponPrice;
import cn.shoptnt.model.trade.order.dto.OrderDTO;
import cn.shoptnt.model.trade.order.vo.CommandResult;
import cn.shoptnt.service.trade.order.command.OrderCreateCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券Command
 *
 * @author snow
 * @version 1.0.0
 * 2022-01-22 15:25:00
 */
@Service
public class CouponUseCommand implements OrderCreateCommand {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 购物车优惠券管理
     */
    @Autowired
    private MemberClient memberClient;

    /**
     * 会员优惠券管理
     */
    @Autowired
    private CouponClient couponClient;


    @Override
    public CommandResult execute(OrderDTO orderDTO) {
        CommandResult result = new CommandResult(true, "成功");

        result.setRollback(this, orderDTO);

        if (CollUtil.isEmpty(orderDTO.getGoodsCouponPrices())) {
            return result;
        }
        //构建默认执行结果
        try {
            //用于记录使用的优惠券id，重复的不记录，
            List<Long> couponList = orderDTO.getGoodsCouponPrices()
                    .stream().map(GoodsCouponPrice::getMemberCouponId)
                    .distinct()
                    .collect(Collectors.toList());
            for (Long id : couponList) {
                //使用优惠券
                this.memberClient.usedCoupon(id, orderDTO.getSn());
                //查询该使用了的优惠券
                MemberCoupon memberCoupon = this.memberClient.getModel(orderDTO.getMemberId(), id);
                //修改店铺已经使用优惠券数量
                this.couponClient.addUsedNum(memberCoupon.getCouponId());
            }

            logger.debug("更改优惠券的状态完成");

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更改优惠券的状态出错", e);

            return new CommandResult(false, "更改优惠券的状态出错");
        }

        return result;
    }

    @Override
    public void rollback(OrderDTO order) {

    }
}
